package org.chen.service;

import org.chen.common.UserUtils;
import org.chen.mapper.RolesMapper;
import org.chen.mapper.UserMapper;
import org.chen.mapper.UserRolesMapper;
import org.chen.model.Roles;
import org.chen.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class UserService implements UserDetailsService {
    @Autowired
    UserMapper userMapper;

    @Autowired
    RolesMapper rolesMapper;

    @Autowired
    UserRolesMapper userRolesMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //获取用户信息
        User user = userMapper.loadUserByUsername(username);
        if (user==null){
            throw new UsernameNotFoundException("用户不存在");
        }
        //获取用户的角色信息,并返回存入user中
        List<Roles> roles = rolesMapper.getRolesByUid(user.getId());
        user.setRoles(roles);
        return user;
    }

    public List<User> getAllUsers(String keyword){
        return userMapper.getAllUsers(UserUtils.getCurrentUserId(),keyword);
    }

    public User getUserById(Integer id){
        return userMapper.getUserById(id);
    }

    public int enableUserById(Integer id, Boolean enabled){
        return userMapper.enableUserById(id,enabled);
    }

    public int delUserById(Integer id){
        return userMapper.delUserById(id);
    }

    @Transactional
    public int updateUserRoles(Integer uid,Integer[] rids){
        userRolesMapper.delUserRolesByUid(uid);
        return userRolesMapper.addUserRolesByUid(rids, uid);
    }

}
